package com.hl.card.modular.pack.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.remote.resolve.RemoteService;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.common.remote.user.RemoteUserService;
import com.hl.card.common.util.HttpRequestUtil;
import com.hl.card.common.util.PhoneFormatCheckUtils;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.pack.dto.AwardUser;
import com.hl.card.modular.pack.service.PackUserService;
import com.hl.card.modular.pack.service.RewardLogin;
import com.hl.card.modular.pack.service.UserDataService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api/luser")
public class LoginUserController {
    private static final Logger logger = LoggerFactory.getLogger(UserDataController.class);
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private UserDataService userDataService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RewardLogin rewardLogin;

    @Autowired
    private PackUserService packUserService;

    @Value("${uc.login}")
    private String loginUrl;
    @Value("${uc.center}")
    private String userCenterUrl;
    @PostMapping("login")
    public Object login(RemoteUser user, HttpServletRequest httpServletRequest, HttpSession session) {
        String loginAccount=user.getLoginAccount();
        String loginPwd=user.getLoginPwd();
        String gustId= httpServletRequest.getParameter("gustId");
        String vrifyCode= httpServletRequest.getParameter("vrifyCode");
        Map<String,Object> map= remoteService.login(loginAccount,loginPwd,gustId,vrifyCode);
        Object code= map.get("code");
        if(code.equals("0")){
            String url=userCenterUrl+":808/login";
            String param="username="+loginAccount+"&password="+loginPwd;
            String result= HttpRequestUtil.sendGet(url,param);
            JSONObject jsonObject=JSON.parseObject(result);
            jsonObject.put("code","0");
            return jsonObject;
        }else{
         return map;
        }
    }

    /**
     * 邀请码邀请用户注册
     * @param phone
     * @param phoneCode
     * @param regCode
     * @return
     */
    @PostMapping("/wx/regByCode")
    public Object register(String phone, String phoneCode,String regCode){
        String salt= ShiroKit.getRandomSalt(5);
        String mobilePhone=phone;
        ResponseObject responseObject=new ResponseObject();
        if(StringUtils.isBlank(phone)||StringUtils.isBlank(phoneCode)||StringUtils.isBlank(regCode)){
            responseObject.setErroCode(0);
            responseObject.setData("用户手机号，验证码，邀请码都不能为空");
            return responseObject;
        }
        //注册卡包用户
        /**
         * 查询平台是否有此用户
         * 没有创建
         */
        ResponseObject res = rewardLogin.checkRegCode(regCode);
        Boolean b = (Boolean) res.getData();//发送MQ loginUserService.checkRegCode(regCode);
        if(!b){
            responseObject.setErroCode(0);
            responseObject.setData("注册推荐码不存在");
            return responseObject;
        }
        JSONObject json = remoteUserService.findSsoUserByPhone(mobilePhone);
        if(json.getString("code").equals("0")){//用户存在
            responseObject.setErroCode(0);
            responseObject.setData("用户已存在");
        }
        if(json.getString("code").equals("3")){//用户不存在
            RemoteUser newRemoteUser=new RemoteUser();
            newRemoteUser.setLoginAccount(mobilePhone);
            newRemoteUser.setMobilePhone(mobilePhone);
            //创建远程用户
            JSONObject useroObj=remoteUserService.regSsoUser(mobilePhone,phoneCode);
            if(!useroObj.getString("code").equals("0")){
                responseObject.setErroCode(0);
                responseObject.setData(useroObj.getString("msg"));
            }else{
                String userid=useroObj.getString("userId");
                newRemoteUser.setUserId(userid);
                User newUser=new User();
                newUser=userDataService.ssouserToCarPackUser(newRemoteUser,newUser);
                newUser.setRefer_reg_code(regCode);
                newUser.setSalt(salt);
                //创建本地用户
                userDataService.insert(newUser);
                responseObject.setErroCode(1);
                //群主或者群主推荐人发奖励，新增群主功能
                Map resultMap= packUserService.zoneUserAwardThree(regCode,newUser.getUserId());
                Map awardResult=new HashMap();
                awardResult.put("type","0");
//              Map resultMap= packUserService.zoneUserAwardResult(regCode,newUser.getUserId());
//              boolean isZoneAward= (boolean) resultMap.get("isZoneAward");
//              Map awardResult=new HashMap();
//              if(!isZoneAward){//普通用户进行奖励
//                    logger.debug("/api/init: 对受邀注册行为进行奖励");
//                    AwardUser rewardDto=new AwardUser();
//                    rewardDto.setRegDate(new Date());
//                    rewardDto.setRegCode(regCode);
//                    rewardDto.setUserId(newUser.getUserId());
//                    rewardLogin.reward(JSON.toJSONString(rewardDto));
//                    awardResult.put("type","0");
//                }else{//返回群奖励个数
//                  awardResult.put("type","1");
//                  awardResult.put("award",resultMap.get("award"));
//              }
                /**
                 *奖励规则变更,
                 * 1.不再判断是否为群主,
                 * 2.不再发送比豆奖励,
                 * 3.奖励规则：未通过邀请经理70htl
                 *
                 */
                responseObject.setData(awardResult);
                Random random = new Random();
                long a=random.nextInt(3)+3;
                stringRedisTemplate.opsForValue().increment("regUserNum",a);
            }
        }
        return  responseObject;
    }
    /***
     * 用户手机验证码 图形验证码 注册 并登陆
     * @param phone
     * @param code
     * @return code 1 正常返回 code 0 错误返回(手机验证码不正确)
     */
    @GetMapping(value = "/registerWithCode")
    public Object codeLogin(String phone,String code,String gustId,String verifyCode,@RequestParam(name="regCode",required = false) String regCode){
        regCode=null;
        AwardUser rewardDto=new AwardUser();
        rewardDto.setRegDate(new Date());
        rewardDto.setRegCode(regCode);
        String salt=ShiroKit.getRandomSalt(5);
        /**
         * 查询平台是否有此用户
         * 没有创建
         */
        if(StringUtils.isNotBlank(regCode)){
            User regUser = userDataService.findUserByRedCode(regCode);
            if(null==regUser){
                Map map=new HashMap();
                map.put("code","4");
                map.put("msg","无效的邀请码");
                return map;
            }
        }
        if(StringUtils.isBlank(phone)||StringUtils.isBlank(code)){
            Map map=new HashMap();
            map.put("code","5");
            map.put("msg","用户手机号，验证码，邀请码都不能为空");
            return map;
        }
        JSONObject json = remoteUserService.findSsoUserByPhone(phone);
        if(json.getString("code").equals("0")){//用户存在
            String str=	JSON.toJSONString(json.get("user"));
            RemoteUser remoteUser= JSON.parseObject(str,RemoteUser.class);
            String userId=remoteUser.getUserId();
            Wrapper<User> wrapper=new EntityWrapper<User>();
            wrapper.eq("user_id",userId);
            User user=userDataService.selectOne(wrapper);
            if(null==user){
             User newUser=new User();
             newUser = userDataService.ssouserToCarPackUser(remoteUser, newUser);
             newUser.setRefer_reg_code(regCode);
             newUser.setSalt(salt);
             userDataService.insert(newUser);
             rewardDto.setUserId(userId);
             rewardDto.setRegDate(remoteUser.getCreateTime());
            }
        }
        if(json.getString("code").equals("3")){//用户不存在
            RemoteUser newRemoteUser=new RemoteUser();
            newRemoteUser.setLoginAccount(phone);
            newRemoteUser.setMobilePhone(phone);
            //创建远程用户
            JSONObject useroObj=remoteUserService.regSsoUser(phone,code);
            if(!useroObj.getString("code").equals("0")){
                Map map=new HashMap();
                map.put("code","0");
                map.put("msg",useroObj.getString("msg"));
                return useroObj;
            }
            String userid=useroObj.getString("userId");
            newRemoteUser.setUserId(userid);
            User newUser=new User();
            newUser.setRefer_reg_code(regCode);
            newUser.setDeptid(1001);
            newUser=userDataService.ssouserToCarPackUser(newRemoteUser,newUser);
            newUser.setSalt(salt);
            userDataService.insert(newUser);
            rewardDto.setUserId(userid);
        }
//        boolean isZoneAward;
        if(StringUtils.isBlank(regCode)) {//进行普通注册奖励
            Map resultMap= packUserService.zoneUserAwardOne(rewardDto.getUserId());//对群主奖励
//            isZoneAward = false;
        }else {
            //非微信注册来源的用户，不提供HTL奖励
//            isZoneAward = packUserService.zoneUserAward(regCode, rewardDto.getUserId());
//            Map resultMap= packUserService.zoneUserAwardResult(regCode,rewardDto.getUserId());//对群主奖励
//            isZoneAward= (boolean) resultMap.get("isZoneAward");
            Map resultMap= packUserService.zoneUserAwardThree(regCode,rewardDto.getUserId());
        }
//        if(!isZoneAward){//普通用户进行奖励
//            //发送MQ loginUserService.reward(rewardDto);
//            rewardLogin.reward(JSON.toJSONString(rewardDto));
//        }
        //新接口直接登录
        String param="username="+phone+"&password="+code+"&appid=pcode";
        String ret=HttpRequestUtil.sendPost(loginUrl,param,false);
        JSONObject jsonObject=JSON.parseObject(ret);
        return  jsonObject;
    }
    @GetMapping(value = "/retryWxCommunityAward")
    public Object retryWxCommunityAward(){
        boolean isZoneAward;
        isZoneAward = packUserService.zoneUserAwardRetry();//对群主奖励
        return  "奖励成功";
    }

    @GetMapping(value = "/retryWxCommunityAwardByRecommender")
    public Object retryWxCommunityAwardByRecommender(){
        boolean isZoneAward;
        isZoneAward = packUserService.zoneUserAwardRetryByRecommender();//对群主奖励
        return  "奖励成功";
    }

    @GetMapping(value = "/checkCommunityAdminInfo")
    public Object checkCommunityAdminInfo(){
        boolean isZoneAward;
        isZoneAward = packUserService.checkCommunityAdminInfo();//对群主奖励
        return  "奖励成功";
    }

    @GetMapping(value = "/retryCommunityAdminBuildAward")
    public Object retryCommunityAdminBuildAward(){
//        boolean isZoneAward;
//        isZoneAward = packUserService.retryCommunityAdminBuildAward();//对群主奖励
        return  "奖励成功";
    }

    @GetMapping(value = "/checkCommunityAwardForFreeze")
    public Object checkCommunityAwardForFreeze(){
        boolean isZoneAward;
        isZoneAward = packUserService.checkCommunityAwardForFreeze();//对群主奖励
        return  "奖励成功";
    }

    @GetMapping("getRegUserNum")
    public ResponseObject getRegUserNum(String regCode){
      String num=stringRedisTemplate.opsForValue().get("regUserNum");
      String userNum="";
      if(StringUtils.isBlank(num)){
          userNum= 536878+"";
      }else{
          userNum= (536878+Integer.parseInt(num))+"";
      }
      ResponseObject responseObject=new ResponseObject();
      ResponseObject res = rewardLogin.getUserByRegCode(regCode);
      JSONObject userObj = (JSONObject) res.getData();
      User user= JSONObject.parseObject(userObj.toJSONString(), User.class);//loginUserService.getUserByRegCode(regCode);
      Map<String,String> map=new HashMap();
      map.put("userNum",userNum);
      if(null!=user){
          map.put("phone", PhoneFormatCheckUtils.playCode(user.getPhone()));
          map.put("msg","请求成功");
          responseObject.setData(map);
          responseObject.setErroCode(0);
      }else {
          map.put("msg","注册邀请码不正确");
          map.put("phone","");
          responseObject.setData(map);
          responseObject.setErroCode(1);
      }
      return  responseObject;
    }
    @GetMapping("checkRegType")
    public ResponseObject CheckRegCodeType(String regCode){
        int type=0;//0 普通用户 ，1群用户
        int errorCode=1;
        ResponseObject responseObject=new ResponseObject();
        User user1=userDataService.findUserByRedCode(regCode);
      if(user1==null){//无效推荐码
          errorCode=0;
      }else{
         String iscommunityUser=user1.getIscommunityUser();
         String  refer_reg_code=user1.getRefer_reg_code();
         if(iscommunityUser!=null&&iscommunityUser.equals("1")){//是群主
             type=1;
         }else if(!StringUtils.isBlank(refer_reg_code)){//本人不是群主
              User user2=userDataService.findUserByRedCode(refer_reg_code);
              if(user2 != null) {
                  if (user2.getIscommunityUser() != null && user2.getIscommunityUser().equals("1")) {//上级是群主
                      type = 1;
                  }
              }
          }
      }
        responseObject.setErroCode(errorCode);
        responseObject.setData(type);
        return  responseObject;
    }

    @RequestMapping(value = "/checkUserType")
    public ResponseObject checkUserType(@RequestParam String userId){
        int type=0;//0 普通用户 ，1群用户
        ResponseObject res = new ResponseObject();
        res.setErroCode(0);

        Wrapper<User> wrapperuser = new EntityWrapper<User>();
        wrapperuser.eq("user_id", userId);
        User parentUser = userDataService.selectOne(wrapperuser);
        if(parentUser == null) {
            res.setData("用户不存在");
            return res;
        }
        String iscommunityUser=parentUser.getIscommunityUser();
        if(iscommunityUser!=null&&iscommunityUser.equals("1")){//是群主
            type=1;
        }
        res.setErroCode(1);
        res.setData(type);
        return res;
    }

    @RequestMapping(value = "/getUserById")
    public User getUserByUserId(String userid){
        Wrapper<User> wrapperuser = new EntityWrapper<User>();
        wrapperuser.eq("user_id", userid);
        User parentUser = userDataService.selectOne(wrapperuser);
        return parentUser;
    }

    @RequestMapping(value = "/getUserByRegCode")
    public User getUserByRegCode(String regCode){
        Wrapper<User> wrapperuser = new EntityWrapper<User>();
        wrapperuser.eq("reg_code", regCode);
        User parentUser = userDataService.selectOne(wrapperuser);
        return parentUser;
    }
    /**
     * 有限制更新，供内部项目调用,此方法有更新风险
     * @return
     */
    @RequestMapping(value = "/updatePartial")
    public String updatePartial(@RequestBody User user) {
        if(!StringUtils.isBlank(user.getUserId())){
            User userForUp=userDataService.selectByUserId(user.getUserId());
           String refCode=user.getRefer_reg_code();
            if(!StringUtils.isBlank(refCode)){
                userForUp.setRefer_reg_code(refCode);
            }
            boolean i=userDataService.updateById(userForUp);
            if(i){
                System.out.println("用户："+user.getUserId()+"的父类更新到："+user.getRefer_reg_code());
            }
        }
        return "";
    }
}